<template>
  <el-cascader
    v-if="!isDict"
    v-bind="$attrs"
    v-on="$listeners"
    v-model="v_value"
    clearable
    filterable
    :options="cityOptions"
    :show-all-levels="showAllLevels"
    @change="handlerChange"
  ></el-cascader>
  <div v-else>{{ dictData || data }}</div>
</template>

<script>
import { getRegionTree } from '@/api/common';

export default {
  inheritAttrs: false,
  props: {
    data: {
      type: [Array, String, Object],
      default: () => [],
    },
    // 是否作为回显字典用
    isDict: {
      type: Boolean,
      default: false,
    },
    // 获取区域树层级（默认到省市）
    treeLevel: {
      type: Number,
      default: 2,
    },
    // 是否只返回最后一级
    showAllLevels: {
      type: Boolean,
      default: true,
    },
  },
  model: {
    prop: 'data',
    event: 'inputs',
  },
  data() {
    return {
      v_value: '',
      cityOptions: [],
      dictData: '',
    };
  },
  watch: {
    data: {
      deep: true,
      immediate: true,
      handler() {
        this.initData();
      },
    },
  },
  created() {
    this.getRegionTree();
  },
  methods: {
    initData() {
      if (this.isDict) {
        this.dictData = this.data
          .map((item) => this.getLabelByValue(item, this.cityOptions))
          .join(' / ');
      } else {
        this.v_value = this.data?.data || this.data;
      }
    },
    async getRegionTree() {
      const res = await getRegionTree(this.treeLevel);
      // 将原始数据转换为 el-cascader 需要的格式
      this.cityOptions = this.formatOptions(res.data);
    },
    formatOptions(data) {
      // 将原始数据转化为 el-cascader 组件所需的嵌套结构
      return data.map((item) => ({
        value: item.code, // 或者根据实际情况可能是 item.id
        label: item.name,
        ...(item.child && { children: this.formatOptions(item.child) }), // 使用展开运算符(...)仅在item.child存在时添加children属性
      }));
    },
    getLabelByValue(value, options) {
      for (const option of options) {
        if (option.value === value) {
          return option.label;
        }
        if (option.children) {
          const childLabel = this.getLabelByValue(value, option.children);
          if (childLabel) {
            return childLabel;
          }
        }
      }
      return '';
    },
    handlerChange(value) {
      let selectedLabels = '';
      if (Array.isArray(value[0])) {
        selectedLabels = value.map((item) => {
          return {
            province: item.map((itemT) => this.getLabelByValue(itemT, this.cityOptions))[0],
            city: item.map((itemT) => this.getLabelByValue(itemT, this.cityOptions))[1],
            district: item.map((itemT) => this.getLabelByValue(itemT, this.cityOptions))[2],
          };
        });
      } else {
        let label = value.map((item) => this.getLabelByValue(item, this.cityOptions));
        selectedLabels = {
          province: label[0],
          city: label[1],
          district: label[2],
        };
      }

      this.$emit('inputs', {
        data: value,
        formatData: selectedLabels,
      });
    },
  },
};
</script>
